import {defineStore} from 'pinia';
import {ref} from 'vue';
import {loginUser, registerUser, sendCode, loginByPhone} from '@/router/api.js';
import {useRouter} from 'vue-router';
import {decodeToken} from "@/utils/JwtUtil.js";


export const useUserStore = defineStore('user', () => {
    const router = useRouter();
    const userInfo = ref({
        id: '',
        account: '',
        password: '',
        email: '',
        telphone: '',
        points: '',
        money: '',
        avatar: '',
        reg_time: '',
        status: '',
        last_login_time: '',
        last_login_ip: '',
    });
    const token = ref(null);
    const errorMessage = ref(null);
    const isLogin = ref(false);
    const countdown = ref(0); // 新增倒计时状态

    // 登录成功后的处理逻辑
    const handleLoginSuccess = (data) => {
        token.value = data.token;
        userInfo.value = data.info;
        errorMessage.value = null;
    };

    // 发送验证码方法
    const sendCodeByPhone = async (phone) => {
        try {
            const response = await sendCode(phone);
            const {data, status, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }
            return data;
        } catch (err) {
            errorMessage.value = err.response?.data?.message || err.message || '验证码发送失败';
            throw err;
        }
    };

    // 手机验证码登录方法
    const phoneLogin = async (phone, code, last_login_ip) => {
        try {
            const response = await loginByPhone(phone, code, last_login_ip);

            const {status, data, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }

            // 处理登录成功逻辑
            handleLoginSuccess(data);
            isLogin.value = true;

            // 跳转到首页
            await router.replace('/');
        } catch (err) {
            errorMessage.value = err.response?.data?.message || err.message || '登录失败';
            throw err;
        }
    };

    // 账户密码登录方法
    const login = async (credentials) => {
        try {
            const response = await loginUser(credentials);
            const {status, data, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }

            handleLoginSuccess(data);
            isLogin.value = true;
            // 登录成功后跳转到首页
            await router.replace('/');
        } catch (err) {
            // 捕获到后端的错误信息时，更新 errorMessage
            errorMessage.value = err.response?.data?.message || err.message || '登录失败';
            throw err;
        }
    };

    // 注册方法
    const register = async (credentials) => {
        try {
            const response = await registerUser(credentials);
            const {status, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }
        } catch (error) {
            errorMessage.value = err.response?.data?.message || err.message || '注册失败';
            throw err;
        }
    }

    // 退出登录方法
    const logout = () => {
        localStorage.removeItem('user');
        sessionStorage.removeItem('user');
        token.value = null;
        userInfo.value = null;
        isLogin.value = false;
    }

    // 添加校验方法
    const checkTokenExpiration = () => {
        if (!token.value) return false
        const decoded = decodeToken(token.value)
        if (!decoded || Date.now() > decoded.exp) {
            logout()
            return false
        }
        return true
    }

    return {
        userInfo,
        token,
        errorMessage,
        isLogin,
        countdown,
        sendCodeByPhone,
        phoneLogin,
        login,
        register,
        logout,
        checkTokenExpiration
    };
}, {
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: sessionStorage,
                paths: ['token', 'userInfo'],
                /*serializer: {
                    // 💡 可选加密
                    serialize: (value) => encrypt(JSON.stringify(value)),
                    deserialize: (value) => JSON.parse(decrypt(value))
                }*/
            },
        ],
    },
});
